# coding: utf-8
from typing import Literal

from PySide6.QtCore import QSize
from PySide6.QtGui import QResizeEvent
from PySide6.QtWidgets import QApplication, QWidget
from qeventmanager import qevent_manager
from qfluentwidgets import SplashScreen, FluentIcon as FIF, NavigationItemPosition, InfoBar, IndeterminateProgressRing

from common import SingleIcon, signalBus, create_session, init_create_table
from common.server import VideoModel
from components import FluentWindow
from ..class_interface import ClassInterface
from ..download_interface import DownloadInterface
from ..home_interface import HomeInterface
from ..listing_interface import ListingInterface
from ..min_video_interface import MinVideoInterface
from ..search_interface import SearchInterface
from ..setting_interface import SettingInterface
from ..video_interface import VideoInterface
from ..vod_interface import VodInterface


class MainWindow(FluentWindow):
    def __init__(self):
        super().__init__()
        self.progressRing = IndeterminateProgressRing(self)
        self.__initWidgets()
        # 主窗口
        self.videoInterface = VideoInterface(self)
        # 子页面接口
        self.homeInterface = HomeInterface(self)
        self.searchInterface = SearchInterface(self)
        self.classInterface = ClassInterface(self)
        self.vodInterface = VodInterface(self)
        self.listingInterface = ListingInterface(self)
        self.minVideoInterface = MinVideoInterface(self)
        self.downloadInterface = DownloadInterface(self)
        self.settingInterface = SettingInterface(self)

        self.__initSubWidgets()
        self.__connectSignals()

    def __initWidgets(self):
        self.setMinimumSize(1000, 600)
        self.setWindowIcon(SingleIcon.LOGO_PNG.icon())
        self.setWindowTitle('香蕉视频')

        # 创建启动画面
        self.splashScreen = SplashScreen(self.windowIcon(), self)
        self.splashScreen.setIconSize(QSize(106, 106))
        self.splashScreen.raise_()

        desktop = QApplication.primaryScreen().availableGeometry()
        w, h = desktop.width(), desktop.height()
        self.move(w // 2 - self.width() // 2, h // 2 - self.height() // 2)
        self.show()

        # 创建数据库连接
        init_create_table()
        qevent_manager.setDbSession(create_session())

        QApplication.processEvents()
        self.splashScreen.finish()
        self.titleBar.raise_()
        # 显示进度条
        self.progressRing.setFixedSize(60, 60)
        self.progressRing.raise_()
        self.progressRing.hide()

    def __initSubWidgets(self):
        self.addTotalWidget(self.videoInterface)
        # 添加子页面
        self.addSubInterface(self.homeInterface, FIF.HOME, ' 主页 ')
        self.addSubInterface(self.searchInterface, FIF.SEARCH, ' 搜索 ')
        self.addSubInterface(self.listingInterface, FIF.MOVIE, ' 频道 ')
        self.addSubInterface(self.vodInterface, FIF.CALORIES, ' 热点 ')
        self.addSubInterface(self.classInterface, FIF.APPLICATION, ' 分类 ')
        self.addSubInterface(self.minVideoInterface, FIF.PLAY, '短视频')
        self.addSubInterface(self.downloadInterface, FIF.DOWNLOAD, ' 下载 ', position=NavigationItemPosition.BOTTOM)
        self.addSubInterface(self.settingInterface, FIF.SETTING, ' 设置 ', position=NavigationItemPosition.BOTTOM)

    def __connectSignals(self):
        signalBus.msgSignal.connect(self.showMsgBox)
        qevent_manager.failed.connect(lambda e: self.showMsgBox('error', str(e)))
        qevent_manager.threadStarted.connect(self.progressRing.show)
        qevent_manager.threadFinished.connect(self.progressRing.hide)

        self.navigationWidget.currentWidgetChanged.connect(self.__onCurrentInterfaceChanged)
        self.videoInterface.closeSignal.connect(self.__onSubWidgetClosed)
        self.videoInterface.showSignal.connect(self.__onSubWidgetShow)
        self.videoInterface.fullScreenChanged.connect(self.__onFullScreenChanged)

    def __onSubWidgetClosed(self, widget: QWidget):
        if widget == self.videoInterface:
            self.setWindowTitle('香蕉视频')
            self.setTotalCurrentWidget(self.navigationWidget)

    def __onSubWidgetShow(self, widget: QWidget, model: VideoModel):
        if widget == self.videoInterface:
            self.setWindowTitle(model.title)
            self.setTotalCurrentWidget(self.videoInterface)

    def __onFullScreenChanged(self, isFullScreen: bool):
        if isFullScreen:
            self.titleBar.hide()
            self.showFullScreen()
        else:
            self.titleBar.show()
            self.showNormal()

    def showMsgBox(self, level: Literal['info', 'success', 'warning', 'error'], msg: str):
        if level == 'info':
            InfoBar.info('提示', msg, duration=2000, parent=self.window())
        elif level == 'success':
            InfoBar.success('成功', msg, duration=2000, parent=self.window())
        elif level == 'warning':
            InfoBar.warning('警告', msg, duration=2000, parent=self.window())
        elif level == 'error':
            InfoBar.error('错误', msg, duration=3000, parent=self.window())

    def resizeEvent(self, event: QResizeEvent):
        super().resizeEvent(event)
        self.progressRing.move((self.width() - self.progressRing.width()) // 2,
                               (self.height() - self.progressRing.height()) // 2)

    def __onCurrentInterfaceChanged(self, widget: QWidget):
        if hasattr(widget, 'init'):
            widget.init()
